/**
 * 使元素居中显示
 * @param this
 * @author julin
 */
var hideType = false;
function center(obj) { 
	obj.css("position","fixed");
	var topMargin = ($(window).height() - obj.height() ) / 2;
	if(topMargin < 0) {
		topMargin = 0;
	}
	obj.css("top", topMargin+ "px");
	obj.css("left", ($(window).width() - obj.width() ) / 2+$(document).scrollLeft() + "px");
}
/*登陆框居中的*/
center($(".want_dai_box"));
center($(".get_finance_box"));
center($(".adjust_one_box"));
center($(".adjust_second_box"));
center($(".finance_result_box"));
center($(".get_finance_second_box"));
center($(".get_finance_last_box"));
center($(".order_sales_box"));
center($(".send_message_box"));
center($(".change_password_box"));
center($(".change_username_box"));
center($(".change_userinfo_box"));
center($(".login_create_box"));
center($(".carActivity_box"));
center($(".change_record_list"));
center($(".province_city_box"));
center($(".index_province_city_box"));
center($(".finance_replace_box"));
center($(".cancel_date_box"));
center($(".group_order_sales_box"));
center($(".group_remind_box"));
center($(".group_remind_pre_box"));
center($(".car_calc_box"));
center($(".advise_agent_box"));
center($(".ccodeDealerMap_box"));
center($(".order_much_remind_box"));
center($(".ccode_remind_box"));
center($(".black_list_box"));
center($(".exemption_clause"));
center($(".offer_material_block_box"));
center($(".exemption_clause"));
if(typeof($(".editSuccess")) != "undefined") {
	center($(".editSuccess"));
}
if(typeof($(".editFailed")) != "undefined") {
	center($(".editFailed"));
}
if(typeof($(".processTip")) != "undefined") {
	center($(".processTip"));
}


/**
 * 弹出窗口的关闭
 * @param this
 * @return 无
 * @author Julin
 */
function close_popup(obj) {
	$(obj).hide();
	$('.zdc').hide();
	
	/*关闭窗口时的倒计时清零*/
	if(obj == '.normal_login_create_box') {
		restartTimer("#normal_get_email_again","#normalGetTelCode");
	} else if(obj == '.login_create_box') {
		restartTimer("#get_email_again","#getTelCode");
	} else if(obj == '.adjust_one_box') {
		restartTimer("#get_pay_email_again","#getPayTelCode");
		
		//获取短信验证码的按钮变化
		$("a#getPayTelCode").css({
			'background' : '#007dc0',
			'border' : '1px solid #007dc0'
		});
		$("a#getPayTelCode").find("span").css("color","#fff");
	} else {
	
	}
	
	$("body").removeClass("noscroll");//禁止后面的滚轮
	
}
/**/
/**
 * 弹出窗口的关闭和打开
 * @param close (关闭的弹窗)
 * @param open （需要打开的弹窗）
 * @author Julin
 */
function open_close_popup(close,open){
	$(close).hide();
	$(open).show();
	
	/*清空原来填写的数据和报错信息*/
	$(open).find("input[type='text']").not("#want_adjust_count").val("");
	$(open).find("input[type='password']").val("");
	$(open).find("textarea").val("");
	$(open).find("div.error_box_info").remove();
	$(open).find("input.field_error_info").removeClass("field_error_info");
}
/**
 * 弹出窗口的打开
 * @param this(所要打开的弹窗)
 * @return this
 * @author Julin
 */
function open_popup(obj) {
	$('.zdc').show();
	$(obj).show();
	
	/*清空原来填写的数据和报错信息*/
	$(obj).find("input[type='text']").not("#want_adjust_count, #fullname").val("");
	$(obj).find("input[type='password']").val("");
	$(obj).find("textarea").val("");
	$(obj).find("div.error_box_info").remove();
	$(obj).find("input.field_error_info").removeClass("field_error_info");
	
	/*隐藏微信的二维码弹出窗*/
	if($("#bdshare_weixin_qrcode_dialog").is(":visible")) {
		$("#bdshare_weixin_qrcode_dialog").hide();
	}
	
	$("body").addClass("noscroll");//禁止后面的滚轮
}
/**
 * 清除掉原来的报错信息
 * @param box (所要清除错误信息的区域)
 * @returns this
 * @author Julin
 */
function removeError(box) {
	$(box).find("div.error_box_info").remove();
	$(box).find("input.field_error_info").removeClass("field_error_info");
	$(box).find("span.field_error_info").removeClass("field_error_info");
	$(box).find("textarea.field_error_info").removeClass("field_error_info");
}


///////////////////////////Vars////////////////////////////////////////////////////////
//问卷题目类型  added by nick
var questionType={
		SINGLE:"single",
		INPUT:"input",
		MULTI:"multi",
		DROPDOWN:"dropdown"
};
//选项类型 added by nick
var optionType=[
		"企业法人代表/股东","个体工商户","自由职业","其他"];
//工作级别默认值 added by nick
var defaultValues={
		ENTERPRISE:{
			value:1,label:"高级",
			option_label:"企业法人",
			url:"/onlinefinance/loan/c1005/4.png"
				},
		BOSS:{
			value:1,
			label:"高级",
			option_label:"企业法人",
			url:"/onlinefinance/loan/c1005/4.png"
				},
		FREEDOM:{
			value:4,
			label:"新人",
			option_label:"自由职业",
			url:"/onlinefinance/loan/c1005/freedom.png"
				},
		OTHER:{
			value:4,
			label:"新人",
			option_label:"自由职业",
			url:"/onlinefinance/loan/c1005/freedom.png"
				}
		
};
//事件类型  added by nick
var EventType={
		COMPLETE:"complete",
		UPDATE_TITLE:"update_title"
};
//年收入默认placeholder added by nick
var placeHolder="示例:100000元";
//月供输入框提示 added by nick
var placeHolder_sub="请输入月供(元)";
var temp_section_count=0;
var $survey,$navigation,$editor,$summary,$current;
//省市数据和当前做题索引 added by nick
var location_data,currentIndex=0;
///////////////////////////Methods //////////////////////////////////////////////////////////
//初始化问卷默认页 For 手机版 已作废 added by nick
function initFirstSection(){
	var section = $("<div class='section'><br/><p class='sc-fnc-title sc-t-center'>简单6步，贷款即刻到手</p><div class='sc-step-3-img'><img src='/mobile_web/media/img/finance/step1.png' /><i class='fa fa-angle-right'></i><img src='/mobile_web/media/img/finance/step2.png' /><i class='fa fa-angle-right'></i><img src='/mobile_web/media/img/finance/step3.png' /></div><div class='sc-step-3-desc'><div>信用测试</div><div>获得信用卷</div><div>报名预约经销商</div></div><br/><div class='sc-step-3-img'><img src='/mobile_web/media/img/finance/step4.png' /><i class='fa fa-angle-right'></i><img src='/mobile_web/media/img/finance/step5.png' /><i class='fa fa-angle-right'></i><img src='/mobile_web/media/img/finance/step6.png' /></div><div class='sc-step-3-desc'><div>到店提交身份证明</div><div>资质审核</div><div>获得贷款</div></div><div class='sc-btn-margin-30-20' style='margin-bottom: 0;'><button id='button' class='emphasized' on='$.fn.fullpage.moveSectionDown();' style='width: 90%;'>测测我能贷多少</button></div></div>");
	$survey.append(section);
}
/**
 *跳转到指定问卷题目
 *@param {index} 指定题目索引
 *@author nick
 */
function jumpTo(index) {
	$survey.fullpage.moveTo(index+1);
}
/**
 *加载问卷
 *@param {_url} 问卷请求url
 *@return 问卷结果
 *@author nick
 */
$.loadSurvey = function(_url) {
	var result;
	/*$.ajax({
		type : "get",
		url : json.js,
		async : false,
		dataType : "json",
		success : function(data) {
			result = data;
		}
	});*/
	return dataEdai;
};
/**
 *判断是否已存在Navigation预览项
 *@param {index} 题目索引
 *@author nick
 */
function isItemExist(index){
	if($navigation.find(".item").length<=index){
		return false;
	}else{
		return true;
	}
}

/**
 *初始化第一个问题选项值
 *@author nick
 */
function initFisrtAnswer() {
	var data = {};
	data.start = (new Date()).Format(SAIC.Global.dateFormat);
	data.question_id = $("#question_0").val();
	data.question_label = "";
	data.value = "";
	data.end = "";
	$survey.data("answer_0",data);
}

/**
 *更新编辑面板
 *param {data} 题目选项
 *@author nick
 */
function updateEditPanel(data){
	var questions=$survey.data("survey").questions;
	var index=data.question_index;
	$current=$editor;
	$editor.data("current",index);
	
	var question=questions[index];
	$editor.find(".title").text((index+1)+"."+question.label);
	var html;
	//var html=$editor.data("q_"+index+"_ui");
	if(typeof(html)==="undefined"){
		//复制问题的HTML及事件
		html=$(".survey .q_"+index).clone(true);
		html.children(".title").empty();
		html.children(".back").remove();
		html.unbind(EventType.COMPLETE,questionCompleteHandler).bind(EventType.COMPLETE,editCompleteHandler);
		html.unbind(EventType.UPDATE_TITLE,updateTitleHandler).bind(EventType.UPDATE_TITLE,updateEditTitileCompleteHandler);
		$(".survey .q_"+index).find(".number_input").unbind("keypress");
	}
	
	var $body=$editor.find(".body");
	$body.empty();
	$body.append(html);
	
	resetEditorQuestion(index);
	$(".mask").show();
	center($editor);
	$editor.show();
	
}

/**
 *关闭编辑面板
 *@author nick
 */
function closeEditPanel(){
	var index=$editor.data("current");
	//隐藏所有错误提示
	$editor.find(".error").hide();
	//$editor.data("q_"+index+"_ui",$editor.children(".body").children().clone(true));
	
	$(".mask").hide();
	$editor.hide();
	$current=$survey;
}

/**
 *获取问题答案数据
 *@author nick
 */
function getAnswer() {
	var question = $survey.data("q_"+getCurrentIndex());
	if(typeof(question)==="undefined"){
		return;
	}
	var data = $survey.data("answer_" + getCurrentIndex());
	if(typeof (data) == "undefined")
	{
		data={};
	}
	if (data.start == "" || typeof (data.start) == "undefined") {
		data.start = (new Date()).Format(SAIC.Global.dateFormat);
	}
	if (data.end == "" || typeof (data.end) == "undefined") {
		data.end = (new Date()).Format(SAIC.Global.dateFormat);
	}
	hideType = false;
	if(isNull(data.hide)){
		//data.hide=false;
	}
	switch(question.type){
	
	case questionType.SINGLE:
		// 如果选中了
		var selected = $(".q_" + getCurrentIndex()).find(".selected");
		
		if ($(selected).length ==1) {
			var option=selected.data("option");
			data.value = option.code;
			data.option_label = option.label;
			data.label = option.desc;
			data.option_url = option.url;
		}else if($(selected).length >1){
			var parent=selected.data("option");
			if(typeof(parent)=="undefined"){
				break;
			}
			selected = $(selected).filter(".sub_option");
			var option=selected.data("option");
			data.value = option.code;
			data.option_label = parent.label;
			data.option_url = option.url;
		}
		break;
	case questionType.DROPDOWN:
		//判断前后两次选的省市是否一致
		var flag_prov=$("#old_province").val()==$("#current_province").val();
		var flag_city=$("#old_city").val()==$("#current_city").val();
		var flag=(flag_prov && flag_city)?"true":"false";
		//得到true 或false后从题目的选项里去匹配 对应选项的值及icon数据
		var optoins=$.grep(question.options,function(item,index){
			return item.label==flag;
			
		});
		var op=optoins[0];
		data.value=op.code;
		data.option_label=op.label=="true"?"是":"否";
		data.option_url=op.url;
		
		break;
	case questionType.MULTI:
		
		var item=$navigation.children().eq(getCurrentIndex()).data("answer");
		
		if(typeof(item)!="undefined"){
			data.value=item.value;
		}else{
			data.value=0;
		}
		break;
	case questionType.INPUT:
		var tmp=$(".q_" + getCurrentIndex()).children(".options").find("input")[0].value;
		if(tmp!=question.options[0].label){
			data.value=tmp;
		}else{
			data.value="";
			data.option_label="0 "+question.options[0].label;
		}
		if(data.value!=""){
			data.option_label=data.value+question.options[0].label;
		}
		data.option_url = question.options[0].url;
		break;
	}
	
	data.question_index=getCurrentIndex();
	data.type = question.type;
	data.question_id = question.code;
	data.question_label = question.label;
	data.question_optional=question.optional;
	$survey.data("answer_"+getCurrentIndex(),data);
	
	if((getCurrentIndex()+1)<getQuestionCount()){
		var next_data = $survey.data("answer_" + (getCurrentIndex()+1));
		if(typeof (next_data) == "undefined")
		{
			next_data={};
			next_data.start=(new Date()).Format(SAIC.Global.dateFormat);
		}
		$survey.data("answer_"+(getCurrentIndex()+1),next_data);
	}
	
	optionHacker(question,data);

}
/**
 * [leaveHandler 问卷跳题离开的事件处理]
 * @param  {[type]} index     [题目索引]
 * @param  {[type]} nextIndex [下一题索引]
 * @param  {[type]} direction [方向]
 * @author nick
 */
function leaveHandler(index,nextIndex,direction){
	//index,nextIndex都是从1开始的
	var newIndex=$(".survey > .section").eq(nextIndex-1).find(".question").data("index");
	var oldIndex=$(".survey > .section").eq(index-1).find(".question").data("index");
	if(newIndex !=undefined){
		currentIndex=oldIndex;
		if(newIndex>oldIndex){
			getAnswer();
		}
		//updateQuestionPreview(newIndex,oldIndex);
	}else if(newIndex==undefined && oldIndex!=undefined){
		currentIndex=oldIndex;
		getAnswer();
		submitSurvey();
	}else{
		currentIndex=-1;
		
	}
	
	currentIndex=newIndex;
	//console.log("新:"+nextIndex+"旧:"+index+"当前:"+currentIndex);
	drawCircle(currentIndex, 8);
}
/**
 * [optionHacker 题目样式固定逻辑处理]
 * @param  {[type]} question [问题信息]
 * @param  {[type]} answer   [答案信息]
 * @author nick
 */
function optionHacker(question,answer){
	if(question.code=="C1007"){
		var index=answer.question_index;
		var $q=$survey.find(".q_"+(index+1)+" .option");
		switch(answer.option_label){
			case "单身":
				$q.removeClass("disabled");
				$($q.get($q.last().index()-1)).addClass("disabled");
			break;
			default:
				$q.removeClass("disabled");
				break;
		}
	}
}

/**
 * 更新问卷导航的Item
 * @param  {[type]} data [答案数据]
 * @return {[type]}      [无]
 * @author nick
 */
function updateNavigationItem(data){
	var $item=$navigation.children().eq(data.question_index);
	$item.data("answer",data);
	
	var answer=$survey.data("answer_"+data.question_index);
	answer.label=data.desc;
	if(answer.type=="multi") {
		answer.value=data.value;
	} else if(answer.type=="input") {
		answer.value=data.value;
		answer.label = data.display;
	} else {
		answer.value=data.code;
	}
	if(typeof(data.parent_label)=="undefined"){
		answer.option_label=data.label;
	}else{
		answer.option_label=data.parent_label;
	}
	
	answer.option_url=data.url;
//	console.log(answer);
	$item.find(".icon >img").attr("src",host+settings.iconPrefix+data.url);
	$item.find(".label").text(data.display);
	
	//if(isNull(data.hide) || (isNull(data.hide)==false &&data.hide==false)){
	if(hideType == false){
		$item.show();
	}else{
		$item.hide();
	}
}

/**
 * 删除问卷导航Item
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function removeNavigationItem(index){
	$navigation.children().eq(index).remove();
}


/**
 * 更新当前题目头部显示的上一题答题信息预览
 * @param  {[type]} index    [题目索引]
 * @param  {[type]} oldIndex [上一题索引]
 * @return {[type]}          [无]
 * @author nick
 */
function updateQuestionPreview(index,oldIndex)
{
	if(typeof(oldIndex)==="undefined"){
		oldIndex=index-1;
	}
	if(oldIndex>=0 && index>oldIndex &&oldIndex<(getQuestionCount()-1)){
		var data=$survey.data("answer_"+oldIndex);
		$(".q_"+index+" .preview").html(data.question_label+":"+data.option_label);
		$(".q_"+index+" .preview").data("backTo",oldIndex+temp_section_count+1);
	}
	
}

/**
 * 重置问题
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function resetQuestion(index){
//	$survey.removeData("answer_"+(index-1));
	var question = $survey.data("q_"+index);
	
	
	
	removeNavigationItem(index);
	switch(question.type){
		case questionType.SINGLE:
			$(".q_"+index+" .option").removeClass("selected").show();
			$(".q_"+index+" .options").slideDown();
			$(".q_"+index+" .sub_container").hide();
			resetQuestionTitle(index);
			break;
		case questionType.MULTI:
			$(".q_"+index+" .option").removeClass("selected");
			$(".q_"+index+" .number_input").val(placeHolder_sub);
			break;
		case questionType.INPUT:
			$(".q_"+index+" .number_input").val(placeHolder);
			break;
	}
	
}

/**
 * 重置编辑面板问题
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function resetEditorQuestion(index){
//	$survey.removeData("answer_"+(index-1));
	var question = $survey.data("q_"+index);
	
	
	
	//removeNavigationItem(index);
	switch(question.type){
		case questionType.SINGLE:
			$editor.find(".q_"+index+" .option").removeClass("selected").show();
			$editor.find(".q_"+index+" .options").slideDown();
			$editor.find(".q_"+index+" .sub_container").hide();
			resetEditQuestionTitle(index);
			break;
		case questionType.MULTI:
			$editor.find(".q_"+index+" .option").removeClass("selected");
			$editor.find(".q_"+index+" .number_input").val(placeHolder_sub);
			break;
		case questionType.INPUT:
			$editor.find(".q_"+index+" .number_input").val(placeHolder);
			break;
	}
	
}

/**
 * 重置问题标题
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function resetQuestionTitle(index){
	var question = $survey.data("q_"+index);
	$title=$(".q_"+index+">.title");
	$title.empty();
	$title.text(question.label);
}

/**
 * 重置编辑面板问题标题
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function resetEditQuestionTitle(index){
	var question = $survey.data("q_"+index);
	$title=$editor.find(".head>.title");
	$title.empty();
	$title.text(question.label);
}

/**
 * 格式化数字,只允许数字,小数点字母中文都不允许
 * @param  {[type]} target [目标输入框]
 * @param  {[type]} flag   [标志位]
 * @return {[type]}        [无]
 * @author nick
 */
function formatNumber(target,flag) {
	//target.value = target.value.replace(/\D/g, '');
	validateNumInput(target, 8, flag);
}

/**
 * 初始化省市数据
 * @return {[type]} [无]
 * @author nick
 */
function initLocationData(){
	$.ajax({
		type : "get",
		url : "/getAllProvinceCity.do",
		dataType : "json",
		success : function(obj) {
			if (obj.code == 1000) {
				location_data=obj.data;
			}
		}
	});
	
}

/**
 * 获取问卷当前页索引
 * @return {[type]} [索引]
 * @author nick
 */
function getCurrentIndex() {
	return currentIndex;
};

/**
 * 问题总数
 * @return {[type]} [题目总数]
 * @author nick
 */
function getQuestionCount() {
	return $survey.find('.section').length;
};

/**
 * 下一题
 * @return {[type]} [无]
 * @author nick
 */
function nav_next() {
	$survey.fullpage.moveSectionDown(); // Go to next slide
};

/**
 * 上一题
 * @param  {[type]} index [题目索引]
 * @return {[type]}       [无]
 * @author nick
 */
function nav_prev(index) {
	
	if(typeof(index)==="number"){
		//重置当前题
		resetQuestion(index);
		//重置上一题
		resetQuestion(index-1);
		$survey.fullpage.moveTo(index);
	}
	else{
		if (getCurrentIndex() > 0) {
			$survey.fullpage.moveSectionUp();
		}
	}
};
/**
 * 提交问卷
 * @return {[type]} [无]
 * @author nick
 */
function submitSurvey(valueExpect) {
	getAnswer();
	var survey = {};
	var root=$survey.data("survey");
	survey.id = root.code;
	survey.ip = $("#clientIp").val();
	survey.client="chexiang_jrpd";
	var answers = new Array();
	
	$.each(root.questions,function(index,item){
		var tmp=$survey.data("answer_"+index);
		if(!(typeof(tmp)==="undefined" && item.optional==1)){
			answers.push(tmp);
		}
		if(!(typeof(tmp)==="undefined")){
			if(!(typeof(tmp.display)==="undefined")){
				delete tmp.display;
			}
			if(!(typeof(tmp.url)==="undefined")){
				delete tmp.url;
			}
			if(!(typeof(tmp.desc)==="undefined")){
				delete tmp.desc;
			}
			if(!(typeof(tmp.code)==="undefined")){
				delete tmp.code;
			}
		}
	});
	survey.answers = answers;
	buildSummary(survey);
	if(validateSurvey(survey)){
		$(".summary").data("survey",survey);
		$(".summary").data("firstPay",valueExpect);
		confirmSubmit();
	}else{
		alert("数据格式不合法");
	}

}
/**
 * 验证是否有题目未答
 * @param  {[type]} data [答案数据]
 * @return {[type]}      [true 或false]
 * @author nick
 */
function validateAnswers(data){
	var flag=true;
//	$.each(data.answers,function(index,item){
//		
//		if( typeof(item)=="undefined" ||item.value=="" || typeof(item.value)=="undefined"){
//			
//			flag= false;
//			return;
//		}
//	});
	if(data.answers.length>=8){
		var marryStatus=data.answers[2];
		var houseStatus=data.answers[3];
		if(marryStatus.option_label=="单身" && houseStatus.option_label=="配偶名下有房产"){
			flag=false;
		}
	}
	return flag;
	
}

/**
 * 确认提交
 * @return {[type]} [无]
 * @author nick
 */

function setCookie(key, value, expireDay) {
    if (expireDay) {
        var date = new Date();
        date.setTime(date.getTime() + expireDay * 24 * 3600 * 1000);
        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/;expires=" + date.toGMTString();
    } else {
        document.cookie = key + "=" + encodeURIComponent(value) + ";path=/";
    }
}

function confirmSubmit() {
	$(".processTip").show();
	var data=$(".summary").data("survey");
	var firstPayData = $(".summary").data("firstPay");
	if(validateAnswers(data)){
		var result = {};
//		result.survey = $.toJSON(data);
		result = $.toJSON(data);
//		setCookie("haoche",result);
//		setCookie("firstPay",firstPayData);
		$("#firstPay").val(firstPayData);
		$("#results").val(result);
		$("#questionForm").submit();
//		$.ajax({
//			type : "post",
//			url : settings.submitUrl,
//			async : false,
//			data : {"result":result},
//			success : settings.submit
//		});
//		settings.submit();
	}else{
		$(".processTip").hide();
		alert("您的婚姻状况与购车地住房情况矛盾,请检查选项.");
	}
	

}
/**
 * [updateAnswers 更新所有答案信息]
 * @return {[type]} [无]
 * @author nick
 */
function updateAnswers(){
	var survey = {};
	var root=$survey.data("survey");
	survey.id = root.code;
	survey.ip = $("#clientIp").val();
	survey.client="chexiang_jrpd";
	var answers = new Array();
	
	$.each(root.questions,function(index,item){
		var tmp=$survey.data("answer_"+index);
		if(!(typeof(tmp)==="undefined" && item.optional==1)){
			answers.push(tmp);
		}
		
	});
	survey.answers = answers;
	$(".summary").data("survey",survey);
}

/**
 * 验证是否是合法数字
 * @param  {[type]} value [数值]
 * @return {[type]}       [true或false]
 * @author nick
 */
function validateNumber(value){
	if(isNaN(value)==false && value>=0){
		return true;
	}else{
		return false;
	}
}

/**
 * 验证年收入
 * @param  {[type]} pay    [月供]
 * @param  {[type]} income [年收入]
 * @return {[type]}        [true 或false]
 * @author nick
 */
function validateIncome(pay,income){
	return income>(pay*12);
}
/**
 * 验证通用金融输入的数字长度
 * @author 张禀奇
 */
function validateLength(val){
	if(parseInt(val) >= 5000){
		if(parseInt(val) <= 500000){
			return true;
		}else{
			return false;
		}
	}else{
		return false;
	}
}
/**
 * 获取总月供
 * @return {[type]} [总月供]
 * @author nick
 */
function getMonthlyPay(){
	var result=0;
	var root=$survey.data("survey");
	$.each(root.questions,function(index,item){
		var tmp=$survey.data("answer_"+index);
		if(!(typeof(tmp)==="undefined")){
			if(tmp.question_id=='C0010'){
				result= tmp.value;
				return false;
			}
		}
		
	});
	return result;
}


///////////////////////////UI Build////////////////////////////////////////////////////////
/**
 * 初始化问卷
 * @param  {[type]} survey [问卷信息]
 * @return {[type]}        [无]
 * @author nick
 */
function buildSurveyHTML(survey) {
	$survey.data("survey", survey);
	var survey_root = $(".survey");
	if(settings.isTouchDevice){
		initFirstSection();
		temp_section_count=1;
	}
	var count = survey.questions.length;
	// 遍历题目
	$.each(survey.questions,function(index, item) {
		var type = item.type;
		var option_li = $("<div />").addClass('section');
		survey_root.append(option_li);
		var option_content = $("<div  class='q_"
				+ index + "'></div>").addClass('question');
		if(index>0){
			var btnBack=$("<label class='back'>返回上一题</label>");
			$(option_content).append(btnBack);
			$(btnBack).data("index",index);
			$(btnBack).bind("click",backToHandler);
		}
		//最后一条阻止添加标题
		if(index<=6){
		$(option_content).append(
				"<div class='title'>"
						+ item.label + "</div>");// 添加标题
		}
		$(option_li).append(option_content);
		option_content.data("index",index);
		$survey.data("q_"+index,item);
		var item_count = item.options.length;
		var options=$('<div />').addClass('options');
		options.data("index",index);
		option_content.append(options);
		switch(type)
		{
			case questionType.SINGLE:
				if(settings.isTouchDevice){
					options.css("width","200px");
					options.css("height",settings.itemHeight*item_count+"px");
				}else{
					options.css("width",(settings.itemWidth+settings.gap)*item_count+"px");
					options.css("height","150px");
					options.css("margin-top","30px");
					options.css("text-align","center");
				}
				
				buildSingleSelectionQuestionHtml(item, options, option_content);
				buildSubContainerHTML(option_content);
				break;
			case questionType.INPUT:
				options.css("height","220px");
				options.css("padding-top","10px");
				//buildInputQuesitonHTML(item,options);下一行追加index索引，用于更改第7题标题位置
				buildInputQuesitonHTML(item,options,index);
				break;
			case questionType.DROPDOWN:
				if(settings.isTouchDevice){
					options = $("<div class='options' style='height:310px;padding-top:10px;'></div>");
				}else{
					options = $("<div class='options' style='height:210px;padding-top:50px;'></div>");
				}
				
				$(option_content).append(options);
				buildDropDownQuestion(location_data,options);
				break;
			case questionType.MULTI:
				options.css("width",(settings.itemWidth+settings.gap)*item_count+"px");
				options.css("height","210px");
				options.css("margin-top","30px");
				
				buildMultiSelectionQuestionHtml(item, options, option_content);
				buildMuiltConfirmHTML(option_content,settings.itemWidth*item_count);
				break;
			
		}
		option_content.bind(EventType.COMPLETE,questionCompleteHandler);
//		buildNextHtml(option_content);
	});
	survey_root.append('<div class="section summary"></div>');
	$summary=$(".summary");
	$survey.bind(EventType.UPDATE_TITLE,updateTitleHandler);
	$current=$survey;
}
/**
 * [buildSubContainerHTML 生成字体html结构]
 * @param  {[type]} root [父题目根节点]
 * @return {[type]}      [无]
 * @author nick
 */
function buildSubContainerHTML(root){
	var html=$("<div />").addClass("sub_container");
	$(html).css("margin-top","30px");
	root.append(html);
}
/**
 * 生成金额输入框
 * @param  {[type]} root  [父题目根节点]
 * @param  {[type]} label [描述]
 * @param  {[type]} flag  [标志位]
 * @return {[type]}       [无]
 * @author nick
 */
//原始参数(root,label,flag)  修改后追加index参数
function buildNumberInput(root,label,flag,numindex){
//	var result="<input value='"+ label+ "' class='number_input' "
//		+ "onpaste='return false;' "
//		+ "onkeyup='formatNumber(this);' "
//		+ "oncontextmenu='return false' "
//		+ "oncopy='return false' "
//		+ "oncut='return false' "
//		+ "onafterpaste='formatNumber(this);' "
//		+ "onFocus=\"if(value=='"+ label+"'){value='';}\" "
//		+ "onBlur=\"if(!value){value='"+label+"';}\"></input>";
	if(numindex===undefined){
		var $html=$("<input />").addClass('number_input').addClass('placeholder');
	}else if(numindex == 7){
		var $html=$("<input id='fill' />,<input id='fillBox' />").addClass('number_input').addClass('placeholder');
	}
	$html.val(label);
	root.append($html);
	$html.bind("paste",function(){
		return false;
	});
	$html.bind("keyup",function(){
		formatNumber(this,flag);
	});
	$html.bind("contextmenu",function(){
		return false;
	});
	$html.bind("copy",function(){
		return false;
	});
	$html.bind("cut",function(){
		return false;
	});
	$html.bind("afterpaste",function(){
		formatNumber(this,flag);
	});
	$html.bind("focus",function(e){
		//恢复输入框默认颜色
		$("#fill").css("border-color","#bfbfbf");
		$("#fillBox").css("border-color","#bfbfbf");
		if($(this).val()==label){
			$(this).val('');
			if($(this).hasClass('placeholder')){
				$(this).removeClass('placeholder');
			}
		}
		e.stopPropagation();
		return false;
	});
	$html.on("blur",function(e){
		if(!$(this).val()){
			$(this).val(label);
			if($(this).hasClass('placeholder')==false){
				$(this).addClass('placeholder');
			}
		}
		e.stopPropagation();
		return false;
	});
	$html.on("click",function(e){
		e.stopPropagation();
		return false;
	});
	$error=$("<div />").addClass("error");
	$error.text("请输入有效金额");
	root.append($error);
	$error.hide();
//	+ "onpaste='return false;' "
//	+ "onkeyup='formatNumber(this);' "
//	+ "oncontextmenu='return false' "
//	+ "oncopy='return false' "
//	+ "oncut='return false' "
//	+ "onafterpaste='formatNumber(this);' "
//	+ "onFocus=\"if(value=='"+ label+"'){value='';}\" "
//	+ "onBlur=\"if(!value){value='"+label+"';}\";
	return $html;
}
/**
 * [validateNumInput 验证输入框的值是否合法]
 * @param  {[type]} input   [输入框]
 * @param  {[type]} num     [数值]
 * @param  {[type]} duanxin [标识符]
 * @return {[type]}         [无]
 * @author nick
 */
function validateNumInput(input, num, duanxin){
	var str = $(input).val();
	num=$(input).attr("maxlength");
	if(str.length <= num){
		if(duanxin == true){
				if(str.length <= 1 && !/^[0-9]*$/.test(str)){
					$(input).val("");
				}else if(!/^[0-9]*$/.test(str)){
					$(input).val("");
				}
				if(str.length >=2 && /^0[0-9]/.test(str)){
					$(input).val(str.replace(/^0{0,}/,""));
				}
			
		}else{
			if(str.length <= 1 && !/^[1-9]*$/.test(str)){
				$(input).val("");
			}else if(!/^[0-9]*$/.test(str)){
				$(input).val("");
			}else{
				$(input).val(str.replace(/^0{0,}/,""));
			}
		}
	}else{
		str=str.replace(/^0{0,}/,"");
		$(input).val(str.substr(0, num));
	}
}

/**
 * 生成单选题选项界面
 * @param  {[type]} data    [题目数据]
 * @param  {[type]} options [选项]
 * @param  {[type]} root    [根节点]
 * @return {[type]}         [无]
 * @author nick
 */
function buildSingleSelectionQuestionHtml(data, options, root) {
	
	// 遍历选项
	$.each(data.options,function(index) {
		var option=$('<div />').addClass("option");
		options.append(option);
		var button=$('<button />');
		option.append(button);
		var icon=buildIconHTML(this.url);
		button.append(icon);
		
		var label=$('<span />').addClass("label");
		label.text(this.desc);
		
		button.append(label);
		option.data("option",this);
		buildClearHtml(option);
		option.bind('click', optionClickHanlder);
	});
	buildClearHtml(root);
}

/**
 * 生成多选题选项界面
 * @param  {[type]} data    [题目数据]
 * @param  {[type]} options [选项]
 * @param  {[type]} root    [根节点]
 * @return {[type]}         [无]
 * @author nick
 */
function buildMultiSelectionQuestionHtml(data, options, root) {
	// 遍历选项
	$.each(data.options,function(index) {
		var option=$('<div />').addClass("option");
		options.append(option);
		var button=$('<button />');
		option.append(button);
		var icon=buildIconHTML(this.url);
		button.append(icon);
		
		var label=$('<span />').addClass("label");
		label.text(this.desc);
		
		button.append(label);
		option.data("option",this);
		buildClearHtml(option);
		option.bind('click', optionClickHanlder);
		//若有子选项则生成子选项UI
		if(typeof this.sub_options !="undefined"){
			buildSubInputHTML(option);
		}
	});
	root.addClass("multi");
	buildClearHtml(root);
	
}

/**
 * 生成子选项的输入框界面(默认是隐藏的)
 * @param  {[type]} root [根节点]
 * @return {[type]}      [无]
 * @author nick
 */
function buildSubInputHTML(root){
	var input=buildNumberInput(root,placeHolder_sub,true);
	input.attr("maxlength",5);
	input.bind("keypress",multiInputKeypressHandler);
	root.append('<label class="note">注:如已还完,请输0</label>');
//	$(input).css("display","none");
}


/**
 * 生成多选题的确认框界面
 * @param  {[type]} root  [跟节点]
 * @param  {[type]} width [宽度]
 * @return {[type]}       [无]
 * @author nick
 */
function buildMuiltConfirmHTML(root,width){
	var wrapper=$("<div />").addClass("confirm");
	wrapper.css("width",width+"px");
	root.append(wrapper);
	var $error=$("<div />").addClass("error");
	$error.text("您未选择任何选项,请选择后再提交!");
	$error.css("display","none");
	wrapper.append($error);
	var button=$('<button>下一题</button>');
	button.addClass("emphasized");
	button.css("margin","0 auto");
	//button.css("margin-top","20px");
	button.bind("click",multiConfirmClickHandler);
	
	wrapper.append(button);
	
	
	var index=root.data("index");
	button.data("index",index);
}
/**
 * 生成问卷总览 已作废
 * @param  {[type]} data [问卷数据]
 * @return {[type]}      [无]
 * @author nick
 */
function buildSummary(data) {
	
	$summary.empty();
	$("#circle").hide();
}
/**
 * 生成清除浮动的Html
 * @param  {[type]} root [根节点]
 * @return {[type]}      [无]
 * @author nick
 */
function buildClearHtml(root){
	root.append("<div class='clear'></div>");
}
/**
 * 生成下一个导航的html界面
 * @param  {[type]} root [根节点]
 * @return {[type]}      [无]
 * @author nick
 */
function buildNextHtml(root){
	var next=$('<div />').addClass("next");
	next.html("&nbsp;");
	root.append(next);
}
/**
 * 生成问题Icon的Html
 * @param  {[type]} url [icon url]
 * @return {[type]}     [img结构]
 * @author nick
 */
function buildIconHTML(url){
	var icon=$('<div />').addClass("icon");
	var img=$('<img src="'+host+url+'" />');
	icon.append(img);
	return icon;
}
/**
 * 生成填空题
 * @param  {[type]} data    [题目数据]
 * @param  {[type]} options [选项]
 * @return {[type]}         [无]
 * @author nick
 */
//(data, options)原始参数为data,options追加参数index用于修改第7题标题元素位置
function buildInputQuesitonHTML(data, options,index) {
	var option=$('<div />').addClass("field");
	options.append(option);
	option.data("option",data.options[0]);
	var url = data.options[0].url;
	var icon=buildIconHTML(url);
	option.append(icon);
	var wrapper=$("<div />").addClass("wrapper");
	//追加第七题标题
	if(index==7){
		$(wrapper).append(
				"<div class='title reset-title'>"
						+ data.list[0].label + "</div>");// 添加标题
		$(wrapper).append(
				"<div class='title reset-title-copy'>"
						+ data.list[1].label + "</div>");// 添加标题愿意首付金额
	}
	option.append(wrapper);
	var input_template = buildNumberInput(wrapper,placeHolder,false,index);
//	wrapper.append(input_template);
	var button=$("<button>完成</button>").addClass("survey_button emphasized");
	button.css("width","100px");
	button.css("margin","0 auto");
	wrapper.append(button);
	
	var index=options.data("index");
	button.data("index",index);
	button.bind("click",inputButtonClickHandler);
	input_template.attr("maxlength",8);
	input_template.bind("keypress",inputQuestionKeyPressHandler);
	//input_template.bind("propertychange input",inputQuestionKeyUpHandler);
	wrapper.children(".error").remove();
	buildClearHtml(wrapper);
	wrapper.append("<div class='sorry_tip'>对不起,您的年收入已经不够支付目前的月供了</div>");
	wrapper.append("<div class='sorry_tip_ty'>请输入5000-500000之间的金额</div>");
	$error=$("<div />").addClass("error");
	$error.css("text-align","left");
	$error.text("请输入有效金额");
	wrapper.append($error);
	$error.hide();
}

/**
 * 生成问卷导航每一项的HTML
 * @param  {[type]} data [导航数据]
 * @return {[type]}      [无]
 * @author nick
 */
function buildNavigationItemHTML(data){
	var $item=$('<div />').addClass("item");
	var icon=buildIconHTML(data.url);
	$item.append(icon);
	var label=$('<span />').addClass("label");
	label.text(data.display);
	
	$item.append(label);
	$navigation.append($item);
	
	$item.data("answer",data);
	debug(data);
	//绑定点击事件
	$item.bind("click",navigationItemClickHanler);
	//if(isNull(data.hide) || (isNull(data.hide)==false &&data.hide==false)){
	if(hideType == false){
		$item.show();
	}else{
		$item.hide();
	}
}

/**
 * 生成子单选项界面
 * @param  {[type]} root [根节点]
 * @param  {[type]} data [子题目数据]
 * @return {[type]}      [无]
 * @author nick
 */
function buildSubSingleSelectHTML(root,data){
	var $sub_options=$('<div />').addClass("sub_options");
	$sub_options.css("width",data.sub_options.length*(settings.subOptionWidth+settings.gap)+"px");
	root.append($sub_options);
	var index=root.data("index");
	$sub_options.data("index",index);
	$.each(data.sub_options,function(index,item){
		item.parent_label=data.label;
		buildSubSingleItemHTML($sub_options,item);
	});
	buildClearHtml(root);
}
/**
 * 生成单个子单选项
 * @param  {[type]} root [根节点]
 * @param  {[type]} data [子选项数据]
 * @return {[type]}      [无]
 * @author nick
 */
function buildSubSingleItemHTML(root,data){
	var $sub_option=$("<div />").addClass("sub_option");
	root.append($sub_option);
	var index=root.data("index");
	$sub_option.data("index",index);
	
	
	var button=$('<button />');
	$sub_option.append(button);
	var icon=buildIconHTML(data.url);
	button.append(icon);
	
	var label=$('<span />').addClass("content");
	label.text(data.label);
	button.append(label);
	
	$sub_option.data("option",data);
	$sub_option.bind("click",subOptionClickHandler);
}

/**
 * 生成下拉菜单问题 已作废
 * @param  {[type]} data [题目数据]
 * @param  {[type]} root [根节点]
 * @return {[type]}      [无]
 * @author nick
 */
function buildDropDownQuestion(data,root){
	var hometown=$('<div class="location" />');
	root.append(hometown);
	buildTempTitle("户籍所在地: ",hometown);
	buildDropDown("old_province",hometown);
	
	buildDropDown("old_city",hometown);
	
	var current=$('<div class="location" />');
	root.append(current);
	buildTempTitle("主要工作生活所在地: ",current);
	buildDropDown("current_province",current);
	buildDropDown("current_city",current);
	
	root.append('<button onclick="nav_next();return false;" style="min-width:100px;height:40px;margin-top:10px;" class="survey_button emphasized" >确定</button>');
	//加载省市数据
	if(typeof location_data==="undefined"){
		
		$.ajax({
			type : "get",
			url : "/getAllProvinceCity.do",
			dataType : "json",
			success : function(obj) {
				if (obj.code == 1000) {
					location_data=obj.data;
					bindDropDown($("#old_province"), location_data,function(){
						bindProvinceAndCity($("#old_province"),$("#old_city"));
					});
					bindDropDown($("#current_province"), location_data,function(){
						bindProvinceAndCity($("#current_province"),$("#current_city"));
					});
					initDefaultLocation();
				}
			}
		});
	}
	
	/**
	 * 初始化默认第一个数据
	 * @return {[type]} [无]
	 * @author nick
	 */
	function initDefaultLocation(){
		bindProvinceAndCity($("#old_province"),$("#old_city"));
		bindProvinceAndCity($("#current_province"),$("#current_city"));
	}
	/**
	 * 根据所选省绑定市级列表
	 * @param  {[type]} province [省]
	 * @param  {[type]} city     [市]
	 * @return {[type]}          [无]
	 * @author nick
	 */
	function bindProvinceAndCity(province,city){
		var index=province.get(0).selectedIndex;
		var prov=location_data[index];
		bindDropDown(city,prov.citys);
	}
	/**
	 * 生成标题Span
	 * @param  {[type]} title     [标题]
	 * @param  {[type]} container [容器]
	 * @return {[type]}           [无]
	 * @author nick
	 */
	function buildTempTitle(title,container){
		container.append('<span>'+title+'</span>');
	};
	/**
	 * 生成下拉菜单
	 * @param  {[type]} id        [编号]
	 * @param  {[type]} container [父容器]
	 * @return {[type]}           [无]
	 * @author nick
	 */
	function buildDropDown(id,container){
		var select=$('<select id="'+id+'" />');
		container.append(select);
	};
	/**
	 * 绑定数据到下拉菜单
	 * @param  {[type]}   target   [目标对象]
	 * @param  {[type]}   data     [数据]
	 * @param  {Function} callback [回调函数]
	 * @return {[type]}            [无]
	 * @author nick
	 */
	function bindDropDown(target,data,callback){
		target.empty();
		if(typeof callback ==="function"){
			target.bind("change",callback);
		}
		var op;
		$.each(data,function(index,item){
			op=$('<option value="'+item.code+'">'+item.name+'</option>');
			target.append(op);
		});
	};
	
	
}


/**
 * 更新题目标题
 * （如果是工作信息题目,有自选项的选项需要更新父选项到题目标题中）
 * @param  {[type]} index    [题目索引]
 * @param  {[type]} question [题目信息]
 * @param  {[type]} label    [标题]
 * @return {[type]}          [无]
 * @author nick
 */
function updateQuestionTitle(index,question,label){
	//var data
	var $title=$('.q_'+index+' .title');
	$title.empty();
	var $sub=$("<span >"+label+"</span>");
	$title.append(question+"-");
	$title.append($sub);
	$sub.bind("click",backToParentHandler);
}
/**
 * [updateEditPanelTitile 更新弹窗标题]
 * @param  {[type]} index    [题目索引]
 * @param  {[type]} question [问题]
 * @param  {[type]} label    [标题]
 * @return {[type]}          [无]
 * @author nick
 */
function updateEditPanelTitile(index,question,label){
	//var data
	var $title=$('.head>.title');
	$title.empty();
	var $sub=$("<span >"+label+"</span>");
	$title.append(question+"-");
	$title.append($sub);
	$sub.bind("click",index,editBackToParentHandler);
}

///////////////////////////Event Hanlder///////////////////////////////////////////
/**
 * option点击事件处理函数
 * @return {[type]} [无]
 * @author nick
 */
function optionClickHanlder(){
	//if($.fn.fullpage.getMoveStatus()||$(this).hasClass("disabled")){
	if($(this).hasClass("disabled")){
		return;
	}
	var index=$(this).parent().data("index");
	var question=$survey.data("q_"+index);
	if(question.type==questionType.SINGLE){
		$(this).siblings().each(function(index) {
			$(this).removeClass('selected');
		});
		$(this).addClass('selected');
		//获取当前选项的信息
		var option=$(this).data("option");
		//题目索引
		option.question_index=index;
		option.display=option.desc;
		//是否已存在导航预览
		if(isItemExist(option.question_index)){
			updateNavigationItem(option);
		}else{
			buildNavigationItemHTML(option);
		}
		
		var $container=$current.find(".q_"+index+" .sub_container");
		$container.empty();
		$container.data("index",index);
		//若有子选项则生成子选项UI
		if(typeof option.sub_options !="undefined"){
			var $options=$(".q_"+index+" .options");
			$container.show();
			$options.slideUp();
			$(this).trigger(EventType.UPDATE_TITLE,[index,question.label,option.desc]);
			//updateQuestionTitle(index,question.label,option.desc);
			buildSubSingleSelectHTML($container, option);
		}
		else{
			$(this).trigger(EventType.COMPLETE,[index,option]);
		}
	}
	else{
		//获取当前选项的信息
		var option=$(this).data("option");
		var action=typeof(option.action) ==="string"?option.action:"";
		if($(this).hasClass("selected")){
			$(this).removeClass('selected');
		}else{
			//如果Action为clear的题目则把别的选项重置
			if(action=="clear"){
				$(this).parent().children().removeClass("selected");
			}else{
				//如果Action不是clear则把所有Action为clear的选项重置
				var others=$(this).siblings();
				$.each(others,function(){
					var op=$(this).data("option");
					if(op.action=="clear"){
						$(this).removeClass("selected");
					}
				});
			}
			$(this).addClass('selected');
			
		}
		
		
		
//		var selecteds=
		//题目索引
		option.question_index=index;
		option.display=option.label;
		//是否已存在导航预览
		if(isItemExist(option.question_index)){
			updateNavigationItem(option);
		}else{
			buildNavigationItemHTML(option);
		}
		
		var $container=$current.find(".q_"+index+" .sub_container");
//		$container.empty();
		if(action=="clear" && $(this).hasClass('selected')){
			$(this).parent().siblings(".confirm").children(".emphasized").trigger("click");
		}
	}
		
	
}
/**
 * 导航项点击事件处理函数
 * @return {[type]} [无]
 * @author nick
 */
function navigationItemClickHanler(){
	var data=$(this).data("answer");
	var index=data.question_index;
	updateEditPanel(data);
}
/**
 * 金额输入框旁边确认按钮的点击事件
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function inputButtonClickHandler(event){
	var index=$(this).data("index");
	var $field=$(this).parent().parent('.field');
	var option=$field.data("option");
	var value = $field.find("#fill").val();
	var valueExpect = $field.find("#fillBox").val();
	var $error=$(this).siblings(".error").css("color","#FF0000");
	//移除错误提示
	$(this).parent().removeClass("error");
	$(this).parent().removeClass("error_ty");
	if(validateNumber(value) && validateNumber(valueExpect)){
		if(validateIncome(getMonthlyPay(), value)){
			if(validateLength(valueExpect)){
				option.display=value+option.label;
				option.value=value;
				option.question_index=index;
				if(isItemExist(option.question_index)){
					updateNavigationItem(option);
				}else{
					buildNavigationItemHTML(option);
				}
				drawCircle(8, 8);
				//$(this).trigger("complete");
				submitSurvey(valueExpect);
				$(".survey_button").unbind("click", inputButtonClickHandler);
				$(".survey_button").css({"background-color":"#C8C8C8","border-color":"#A4A4A4","cursor":"initial"});
			}else{
				$(this).parent().addClass("error_ty");
			}
		}else{
			//显示错误提示
			$(this).parent().addClass("error");
		}
	}else{
		if(!validateNumber(value)){
			$("#fill").css("border-color","#FF0000")
		}else if(!validateNumber(valueExpect)){
			$("#fillBox").css("border-color","#FF0000")
		}
		$error.show();
		$error.fadeOut(3000);
	}
	return false;
}
/**
 * [inputConfirm 输入框确认]
 * @param  {[type]} value [输入框]
 * @return {[type]}       [无]
 * @author nick
 */
function inputConfirm(value){
	return confirm("请确认您输入的年收入"+value+"元.");
}

/**
 * 子选项点击事件
 * @return {[type]} [无]
 * @author nick
 */
function subOptionClickHandler(){
	$(this).parent().children().removeClass("selected");
	$(this).parent().addClass("selected");
	$(this).addClass("selected");
	var index=$(this).data("index");
	var option=$(this).data("option");
	option.question_index=index;
	option.display=option.label;
	if(isItemExist(option.question_index)){
		updateNavigationItem(option);
	}else{
		buildNavigationItemHTML(option);
	}
	/************************************/
	/*var question=$survey.data("q_"+index);
	if(question.code=="C1003"){
		getAnswer();
		switch(option.label){
			case "200人以上企业":
			case "50-200人企业":
			case "1-50人以下企业":
				$survey.fullpage.config.onLeave=null;
				$survey.fullpage.silentMoveTo(index+2);
				setDefaultValue(index);
				
				var option=$survey.data("answer_"+(index+1));
				//题目索引
				option.question_index=index+2;
				option.display=option.label;
				option.url=option.option_url;
				option.hide=true;
				//是否已存在导航预览
				if(isItemExist(option.question_index)){
					updateNavigationItem(option);
				}else{
					buildNavigationItemHTML(option);
				}
				currentIndex=index+1;
				getAnswer();
				$survey.fullpage.config.onLeave=leaveHandler;
				nav_next();
				
			break;
			default:
				$(this).trigger(EventType.COMPLETE,[index,option]);
				break;
		}
			
		}else{*/
			$(this).trigger(EventType.COMPLETE,[index,option]);
		//}
}
/**
 * 多选确认按钮点击事件(默认处理逻辑是取所有选中项的子输入框选项的值之和)
 * @return {[type]} [无]
 * @author nick
 */
function multiConfirmClickHandler(){
	var index=$(this).data("index");
	
	//1.取出所有选中项目
	var selecteds=$(this).parent().parent().find(".selected");
	if(selecteds.length<=0){
		var $error=$(this).prev(".error");
		$error.show();
		$error.fadeOut(3000);
		return;
	}
	var label="";
	//总月供
	var value=0;
	var option;
	var isValidated=true;
	$.each(selecteds,function(index){
		option=$(this).data("option");
		if(index==0){
			label+=option.label;
		}else{
			label+=","+option.label;
		}
		//2.判断是否有子选项
		if($(this).children().hasClass("number_input")){
			//3.求和
			var val=parseFloat($(this).children(".number_input").val());
			var error=$(this).children(".error");
			var note=$(this).children(".note");
			/*if(validateNumber(val)){
				value+=val;
			}else{
				error.show();
				note.hide();
				error.fadeOut(3000,function(){
					note.show();
				});
				
				isValidated=false;
			}*/
			value=0;
		}
			
	});
	
	if(option.action!="clear"){
		//label+="月供总额为"+value+"元";
		
		if(selecteds.length==1&& option.label=="信用卡"){
			value=1;
			label="信用卡";
		}
		if(selecteds.length==1&& option.label=="其他类贷款"){
			value=2;
			label="其他类贷款";
		}
		if(selecteds.length>0 && value==0){
			value=2;
		}
	}
	
	
	var result={};
	result.display=label;
	result.label=label;
	result.desc=label;
	result.value=value;
	result.url=option.url;
	result.question_index=index;
	if(isValidated){
		//是否已存在导航预览
		if(isItemExist(index)){
			updateNavigationItem(result);
		}else{
			buildNavigationItemHTML(result);
		}
		
		$(this).trigger(EventType.COMPLETE,index);
	}
}


/**
 * 编辑完成处理函数
 * @param  {[type]} event  [事件]
 * @param  {[type]} index  [索引]
 * @param  {[type]} option [选项]
 * @return {[type]}        [无]
 * @author nick
 */
function editCompleteHandler(event,index,option){
	if(typeof(getCurrentIndex())=="undefined"){
		updateAnswers();
		
	}else{
		var question = $survey.data("q_"+index);
		var answer=$survey.data("answer_"+index);
		optionHacker(question, answer);
		if(question.code=="C1003"){
			var data={};
			data.question_index=index+1;
			if(getCurrentIndex()>(index+1)){
				switch(option.label){
					case "自由职业":
					case "个体工商户":
					case "其他":
					case "200人以上企业":
					case "50-200人企业":
					case "1-50人以下企业":
						//多次编辑传值有问题
							setDefaultValue(index);
							
							var op=$survey.data("answer_"+(index+1));
							//题目索引
							op.question_index=index+1;
							op.display=option.label;
							//op.url=option.option_url;
							//op.hide=true;
							//是否已存在导航预览
							if(isItemExist(op.question_index)){
								updateNavigationItem(op);
							}else{
								buildNavigationItemHTML(op);
							}
							
							getAnswer();
//							console.log(op);
							//currentIndex=index+1;
						break;
					default:
						
						//工薪人士子选项继续编辑后面的题目
						var data={};
						data.question_index=index+1;
						updateEditPanel(data);
						return;
						break;
				}
			}else{
				
				optionHacker(question,answer);
			}
			
		}
		if(question.code=="C1005"){
			//显示选项
			var answer=$survey.data("answer_"+(index));
			//answer.hide=false;
		}
		if(question.code=="C1007"){
			//alert(3);
			//alert(answer.option_label);
			var answerNext = $survey.data("answer_"+(index+1));//下一个问题的答案
			//alert(answerNext.hasOwnProperty("option_label") );//判断含有option_label属性
			if(typeof(answerNext) != "undefined" && answerNext != null && answerNext.hasOwnProperty("option_label") && answerNext.option_label == "配偶名下有房产"){
				var data={};
				data.question_index=index+1;
				if(getCurrentIndex()>(index+1)){
					updateEditPanel(data);
					return;
				}else{
					optionHacker(question,answer);
				}
			}
		}
	}
	
	closeEditPanel();
	$(".editSuccess").children("p").text("修改成功");
	$(".editSuccess").show();
	$(".editSuccess").fadeOut(3000);
	
	
}
/**
 * 完成一题后的处理函数
 * @param  {[type]} event  [事件]
 * @param  {[type]} index  [索引]
 * @param  {[type]} option [选项]
 * @return {[type]}        [无]
 * @author nick
 */
function questionCompleteHandler(event,index,option){
	var question=$survey.data("q_"+index);
	if(question.code=="C1003"){
		getAnswer();
		switch(option.label){
			case "自由职业":
			case "个体工商户":
			case "其他":
			case "200人以上企业":
			case "50-200人企业":
			case "1-50人以下企业":
				$survey.fullpage.config.onLeave=null;
				$survey.fullpage.silentMoveTo(index+2);
				
				setDefaultValue(index);
				
				var option=$survey.data("answer_"+(index+1));
				
				//题目索引
				option.question_index=index+2;
				option.display=option.label;
				option.url=option.option_url;
				if(index == 4){
					hideType = true;
				} else {
					hideType = false;
				}
				//option.hide=true;
				//是否已存在导航预览
				if(isItemExist(option.question_index)){
					updateNavigationItem(option);
				}else{
					buildNavigationItemHTML(option);
				}
				
				getAnswer();
				currentIndex=index+2;
				
				
				$survey.fullpage.config.onLeave=leaveHandler;
				nav_next();
				
			break;
			default:
				nav_next();
			break;
		}
	}else{
			nav_next();
		}
	
}
/**
 * 年收入输入框Keypress事件处理函数
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function inputQuestionKeyPressHandler(event){
	if(event.keyCode=='13'){
		var button=$(this).siblings(".survey_button");
		var index=button.data("index");
		if(index==getCurrentIndex()){
			button.trigger("click");
		}
		
		
		$(this).blur();
		event.preventDefault();
		event.stopPropagation();
		return false;
	}
}
/**
 * [inputQuestionKeyUpHandler 输入框按键弹起事件处理]
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function inputQuestionKeyUpHandler(event){
	if(validateIncome(getMonthlyPay(), $(this).val())==false){
		$(this).parent.addClass("error");
	}
}

/**
 * 多选输入框Keypress事件处理函数
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function multiInputKeypressHandler(event){
	if(event.keyCode=='13'){
		var button=$(this).parent().parent().siblings(".confirm").children("button");
		button.trigger("click");
		$(this).blur();
		event.preventDefault();
		event.stopPropagation();
		return false;
	}

}

/**
 * 点击返回上一题事件处理函数
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function backToHandler(event){
	var index=$(this).data("index");
	var question=$survey.data("q_"+index);
	if(question.code=="C1003" && $(".q_"+index+" .sub_container").is(":visible")){
		//重置当前题
		resetQuestion(index);
		backToParentHandler();
	}else if (question.code=="C0010"){
		var answer=$survey.data("answer_"+(index-2));
		if(isNull(answer.option_label)==false && answer.option_label!="工薪人士"){
			resetQuestion(index);
			$survey.fullpage.silentMoveTo(index);
			resetQuestion(index-2);
			$survey.fullpage.moveSectionUp();
		}else{
			nav_prev(index);
		}
		
	}else{
		nav_prev(index);
	}
}
/**
 * 更新题目标题
 * @param  {[type]} event    [事件]
 * @param  {[type]} index    [索引]
 * @param  {[type]} question [题目信息]
 * @param  {[type]} label    [标题]
 * @return {[type]}          [无]
 * @author nick
 */
function updateTitleHandler(event,index, question, label){
	updateQuestionTitle(index, question, label);
}

/**
 * 更新编辑面板题目标题
 * @param  {[type]} event    [事件]
 * @param  {[type]} index    [索引]
 * @param  {[type]} question [题目信息]
 * @param  {[type]} label    [标题]
 * @return {[type]}          [无]
 * @author nick
 */
function updateEditTitileCompleteHandler(event,index, question, label){
	updateEditPanelTitile(index, question, label);
}


/**
 * 默认返回上一级选项事件处理函数
 * @return {[type]} [无]
 * @author nick
 */
function backToParentHandler(){
	var index=getCurrentIndex();
	var $options=$(".q_"+index+" .options");
	$options.children().removeClass('selected');
	$options.slideDown();
	var question=$survey.data("q_"+index);
	var $title=$(".q_"+index+" .title");
	$title.empty();
	$title.append(question.label);
	$(".q_"+index+" .sub_container").hide();
}

/**
 * 弹窗编辑返回上一级事件处理函数
 * @param  {[type]} event [事件]
 * @return {[type]}       [无]
 * @author nick
 */
function editBackToParentHandler(event){
	var index=event.data;
	var $options=$editor.find(".q_"+index+" .options");
	$options.children().removeClass('selected');
	$options.slideDown();
	var question=$survey.data("q_"+index);
	var $title=$editor.find(".head>.title");
	$title.empty();
	$title.append(question.label);
	$editor.find(".q_"+index+" .sub_container").hide();
}

/**
 * 设置工作职位默认值
 * @param {[type]} index [索引]
 * @author nick
 */
function setDefaultValue(index){
	var answer=$survey.data("answer_"+index);
	var data=$survey.data("answer_"+(index+1));
	switch(answer.option_label){
		case optionType[0]:
			data.code=data.value=defaultValues.ENTERPRISE.value;
			data.desc=data.label=defaultValues.ENTERPRISE.label;
			data.option_label=defaultValues.ENTERPRISE.option_label;
			data.url=data.option_url=defaultValues.ENTERPRISE.url;
			break;
		case optionType[2]:
			data.code=data.value=defaultValues.FREEDOM.value;
			data.desc=data.label=defaultValues.FREEDOM.label;
			data.option_label=defaultValues.FREEDOM.option_label;
			data.url=data.option_url=defaultValues.FREEDOM.url;
			break;
		case optionType[1]:
			data.code=data.value=defaultValues.BOSS.value;
			data.desc=data.label=defaultValues.BOSS.label;
			data.option_label=defaultValues.BOSS.option_label;
			data.url=data.option_url=defaultValues.BOSS.url;
			break;
		case optionType[3]:
			data.code=data.value=defaultValues.OTHER.value;
			data.desc=data.label=defaultValues.OTHER.label;
			data.option_label=defaultValues.OTHER.option_label;
			data.url=data.option_url=defaultValues.OTHER.url;
			break;
		default:
			break;
	}
	
}
/**
 * 调试
 * @param  {[type]} value [输出值]
 * @return {[type]}       [无]
 * @author nick
 */
function debug(value){
//	console.log(value);
}
/**
 * [validateSurvey 验证问卷答案值]
 * @param  {[type]} data [答案]
 * @return {[type]}      [无]
 * @author nick
 */
function validateSurvey(data){
	$.each(data.answers,function(index,item){
		if(checkAnswer(item)==false){
			return false;
		}
	});
	return true;
}
/**
 * [checkAnswer 验证问卷单题答案]
 * @param  {[type]} data [答案]
 * @return {[type]}      [无]
 * @author nick
 */
function checkAnswer(data){
	var result=isNull(data.start) 
		&& isNull(data.end) 
		&& isNull(data.label)
		&& isNull(data.option_label)
		&& isNull(data.value)
		&& isNull(data.question_id)
		&& isNull(data.question_label)
		&& isNull(data.question_optional)
		&& isNull(data.type)
		&& isNull(data.option_url)
		&& isNull(data.question_index);
	return result;
}
/**
 * [isNull 是否为空]
 * @param  {[type]}  value [值]
 * @return {Boolean}       [true 或false]
 * @author nick
 */
function isNull(value){
	return typeof(value)==="undefined";
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符，
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子：
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
// @author nick
Date.prototype.Format = function(fmt) { // author: meizz
	var o = {
		"M+" : this.getMonth() + 1, // 月份
		"d+" : this.getDate(), // 日
		"h+" : this.getHours(), // 小时
		"m+" : this.getMinutes(), // 分
		"s+" : this.getSeconds(), // 秒
		"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
		"S" : this.getMilliseconds()
	// 毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	for ( var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
					: (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
};